# -*-coding:utf-8-*-

import json
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
from tornado.gen import coroutine, Return


def url_compose(path, query=None):
    if query is not None:
        return '%s?%s' % (path, query)
    else:
        return path


@coroutine
def http_get(path, query=None, url_compose_func=url_compose):
    url = url_compose_func(path, query)
    http_client = AsyncHTTPClient()
    result = yield http_client.fetch(url, raise_error=False)
    raise Return(result)


@coroutine
def __http_method(method, path, body=None, query=None, url_compose_func=url_compose, dump_body=True, **kwargs):
    url = url_compose_func(path, query)
    if body is not None and dump_body:
        body = json.dumps(body)
    http_request = HTTPRequest(url, method=method, body=body, **kwargs)
    http_client = AsyncHTTPClient()
    result = yield http_client.fetch(http_request, raise_error=False)
    raise Return(result)


@coroutine
def http_post(path, body=None, query=None, dump_body=True, **kwargs):
    result = yield __http_method('POST', path, body, query, dump_body=dump_body, **kwargs)
    raise Return(result)


@coroutine
def http_put(path, body=None, query=None):
    result = yield __http_method('PUT', path, body, query)
    raise Return(result)


@coroutine
def http_delete(path, body=None, query=None):
    result = yield __http_method('DELETE', path, body, query)
    raise Return(result)
